package com.ambitor.ipro.app.sche;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.DatasetList;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.ambitor.ipro.entities.UninstallSetting;
import com.ambitor.ipro.exceptions.ProException;
import com.ambitor.ipro.service.TopService;
import com.ambitor.ipro.util.Constants;
import com.ambitor.ipro.util.ResultCode;
import com.ambitor.ipro.util.SkyenccUtil;
import com.ambitor.ipro.util.StringUtil;
import com.taobao.api.domain.Item;

public class Uninstaller extends BaseExecutor {

	public Uninstaller(SuperDao superDao, TopService topService) {
		super(superDao, topService);
	}

	@SuppressWarnings("unchecked")
	public void uninstall() {
		logTaskStart();
		try {
			IData userSession = getUserSession();
			int[] result = _uninstall(userSession);
			logTaskEnd(result);
		} catch (ProException e) {
			logTaskQuit(e);
		}
	}

	@SuppressWarnings("unchecked")
	private int[] _uninstall(IData userSession) throws ProException {
		String nick = userSession.getString("NICK");
		String sessionId = userSession.getString("SESSION_ID");
		String place = task.getString("PLACE");
		List<String> iidListToBeUnins = getItemsToUninstall(userSession);
		if (iidListToBeUnins == null || iidListToBeUnins.size() == 0) {
			throw new ProException(ResultCode.BUSSINESS_EXCEPTION,
					"获取待卸载的宝贝为空，请尝试其它卸载方式");
		}
		int errorNum = 0;
		IDataset tradePros = new DatasetList();
		for (String iid : iidListToBeUnins) {
			IData tradePro = new DataMap();
			tradePro.put("BATCH_ID", task.getString("BATCH_ID"));
			tradePro.put("IID", iid);
			tradePro.put("PLACE", task.getString("PLACE"));
			tradePro.put("LOG_TIME", SkyenccUtil.formatDate(new Date()));
			try {
				Long numIid = Long.valueOf(iid);
				topService.uninstallPromotionModule(sessionId, nick, numIid,
						place);
				tradePro.put("TRADE_STATE", Constants.FLAG_YES);// 成功
				tradePro.put("EXP_TYPE", null);
				tradePro.put("EXP_DESC", null);
				tradePro.put("EXP_CODE", null);
				tradePro.put("EXP_MSG", null);
				tradePro.put("EXP_SUB_CODE", null);
				tradePro.put("EXP_SUB_MSG", null);
			} catch (ProException e) {
				errorNum++;
				tradePro.put("TRADE_STATE", Constants.FLAG_NO);// 失败
				tradePro.put("EXP_TYPE", e.getType());
				tradePro.put("EXP_DESC", e.getDesc());
				tradePro.put("EXP_CODE", e.getCode());
				tradePro.put("EXP_MSG", e.getMsg());
				tradePro.put("EXP_SUB_CODE", e.getSubCode());
				tradePro.put("EXP_SUB_MSG", e.getSubMsg());
				continue;
			} finally {
				tradePros.add(tradePro);
			}
		}

		try {
			// deleteItemPros(tradePros);
			insertTradePros(tradePros);
		} catch (Exception exp) {
			logger.error("新增tradePro日志或更新item_pro出现数据库异常", exp);
		}
		return new int[] { iidListToBeUnins.size(), errorNum };
	}

	@SuppressWarnings("unchecked")
	private List<String> getItemsToUninstall(IData userSession)
			throws ProException {
		List<String> iidList = new ArrayList<String>();
		if (retryFlag) {
			IData param = new DataMap();
			param.put("BATCH_ID", task.getString("BATCH_ID"));
			param.put("TRADE_STATE", Constants.FLAG_NO);
			try {
				IDataset dataset = superDao.queryList("TL_P_TRADE_PRO", param);
				for (int i = 0; i < dataset.size(); i++) {
					iidList.add(dataset.get(i, "IID").toString());
				}
				return iidList;
			} catch (Exception e) {
				throw new ProException(ResultCode.DB_EXCEPTION, "获取pro_id="
						+ task.getString("BATCH_ID") + "安装失败宝贝出现异常", e);
			}
		}

		if (UninstallSetting.BATCH_UNINSTALL.equalsIgnoreCase(task
				.getString("UNINSTALL_SETTING"))) {
			return getIidsToUninstall4Batch(userSession);

		} else if (UninstallSetting.ALL_UNINSTALL.equalsIgnoreCase(task
				.getString("UNINSTALL_SETTING"))) {
			String sessionId = userSession.getString("SESSION_ID");
			String nick = userSession.getString("NICK");
			List<Item> itemList = topService.getAllItems(sessionId, nick);
			for (Item item : itemList) {
				iidList.add(item.getNumIid().toString());
			}
		}

		return iidList;
	}

	@SuppressWarnings("unchecked")
	private List<String> getIidsToUninstall4Batch(IData userSession)
			throws ProException {
		IData userPro = getUserPro();
		List<Item> itemList = new ArrayList<Item>();
		List<String> iidList = new ArrayList<String>();
		String installSetting = userPro.getString("INSTALL_SETTING");
		String sessionId = userSession.getString("SESSION_ID");
		String nick = userSession.getString("NICK");
		if ("custom".equals(installSetting)) {
			IData param = new DataMap();
			param.put("PRO_ID", userPro.getString("PRO_ID"));
			// param.put("VALID_FLAG", Constants.FLAG_YES);
			IDataset iidDataset = null;
			try {
				iidDataset = superDao.queryList("TF_P_USER_PRO_SUB", param);
			} catch (Exception e) {
				throw new ProException(ResultCode.DB_EXCEPTION,
						"获取TF_P_USER_PRO_SUB发生数据库异常", e);
			}
			for (int i = 0; i < iidDataset.size(); i++) {
				iidList.add(iidDataset.get(i, "IID").toString());
			}
		} else if ("someCategory".equals(installSetting)) {
			IData param = new DataMap();
			param.put("PRO_ID", userPro.getString("PRO_ID"));
			// param.put("VALID_FLAG", Constants.FLAG_YES);
			IDataset iidDataset = null;
			try {
				iidDataset = superDao.queryList("TF_P_USER_PRO_SUB", param);
			} catch (Exception e) {
				throw new ProException(ResultCode.DB_EXCEPTION,
						"获取TF_P_USER_PRO_SUB发生数据库异常", e);
			}
			StringBuilder sellerCidsSb = new StringBuilder();
			for (int i = 0; i < iidDataset.size(); i++) {
				sellerCidsSb.append(iidDataset.get(i, "CID").toString());
				sellerCidsSb.append(",");
			}
			String sellerCids = StringUtil.trimSuffix(sellerCidsSb.toString(),
					",");
			itemList = topService.getOnSaleItemsOfSpecificSellerCat(sessionId,
					nick, sellerCids);
			for (Item item : itemList) {
				iidList.add(item.getNumIid().toString());
			}
		} else if ("itemCategory".equals(installSetting)) {
			IData param = new DataMap();
			param.put("PRO_ID", userPro.getString("PRO_ID"));
			// param.put("VALID_FLAG", Constants.FLAG_YES);
			IDataset iidDataset = null;
			try {
				iidDataset = superDao.queryList("TF_P_USER_PRO_SUB", param);
			} catch (Exception e) {
				throw new ProException(ResultCode.DB_EXCEPTION,
						"获取TF_P_USER_PRO_SUB发生数据库异常", e);
			}
			StringBuilder itemCidsSb = new StringBuilder();
			for (int i = 0; i < iidDataset.size(); i++) {
				itemCidsSb.append(iidDataset.get(i, "CID").toString());
				itemCidsSb.append(",");
			}
			String itemCids = StringUtil.trimSuffix(itemCidsSb.toString(), ",");

			itemList = topService.getOnSaleItemsOfSpecificItemCat(sessionId,
					nick, itemCids);
			for (Item item : itemList) {
				iidList.add(item.getNumIid().toString());
			}
		} else if ("onSale".equals(installSetting)) {
			itemList = topService.getOnSaleItems(sessionId, nick);
			for (Item item : itemList) {
				iidList.add(item.getNumIid().toString());
			}
		} else if ("all".equals(installSetting)) {
			itemList = topService.getAllItems(sessionId, nick);
			for (Item item : itemList) {
				iidList.add(item.getNumIid().toString());
			}
		}
		return iidList;
	}

	private IData getUserPro() throws ProException {
		IData userPro = null;
		try {
			userPro = superDao.queryByPK("TF_P_USER_PRO_BATCH", task);
		} catch (Exception e) {
			throw new ProException(ResultCode.DB_EXCEPTION,
					"获取TF_P_USER_PRO_BATCH时发生异常", e);
		}
		return userPro;
	}
}
